<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Order as OrderModel;
use app\common\model\GoodsSpec;
use think\Db;
use app\common\library\SearchLog;

/**
 * 订单接口
 * @ApiWeigh (85)
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 创建订单
     * 
     * @ApiTitle    (创建购物车订单)
     * @ApiSummary  (从购物车创建订单并扣减库存)
     * @ApiMethod   (POST)
     * @ApiParams   (name="cart_ids", type="string", required=true, description="购物车ID，多个用逗号分隔，如：1,2,3")
     * @ApiParams   (name="address", type="string", required=true, description="收货地址，详细的收货地址信息")
     * @ApiParams   (name="contact", type="string", required=true, description="收货人姓名")
     * @ApiParams   (name="phone", type="string", required=true, description="收货人手机号码")
     * @ApiParams   (name="remark", type="string", required=false, description="订单备注")
     * @ApiReturn   ({
        "code": 1,
        "msg": "创建成功",
        "data": {
          "order_no": "202401010001"  // 订单编号
        }
      })
     */
    public function create()
    {
        $params = $this->request->post();
        if (empty($params['cart_ids'])) {
            $this->error('请选择要购买的商品');
        }

        $cartIds = explode(',', $params['cart_ids']);
        
        // 获取购物车商品
        $cartList = \app\common\model\Cart::with(['goods', 'spec'])
            ->where('user_id', $this->auth->id)
            ->whereIn('id', $cartIds)
            ->select();
            
        if (empty($cartList)) {
            $this->error('购物车商品不存在');
        }
        Db::startTrans();
        try {
            // 检查商品状态
            foreach ($cartList as $cart) {
                if ($cart->goods->deletetime > 0) {
                    $this->error("商品已被删除");
                }
                if ($cart->goods->status != 1) {
                    $this->error("商品[{$cart->goods->title}]已下架");
                }
            }

            // 创建主订单
            $order = new OrderModel;
            $order->order_no = date('YmdHis') . rand(1000, 9999);
            $order->user_id = $this->auth->id;
            $order->address = $params['address'];
            $order->contact = $params['contact'];
            $order->phone = $params['phone'];
            $order->remark = isset($params['remark']) ? $params['remark'] : ''; // 添加备注
            $order->total_amount = 0;
            $order->freight_amount = 0;

            // 获取会员折扣
            $discount = 1;
            if ($this->auth->id) {
                $user = \app\common\model\User::get($this->auth->id);
                if ($user->vip_expire_time > time()) {
                    // 获取会员折扣配置
                    $vipConfig = \app\common\model\VipConfig::where('id', 1)->find();
                    if ($vipConfig) {
                        $discount = $vipConfig->discount;
                    }
                }
            }

            // 创建订单商品
            $orderItems = [];
            foreach ($cartList as $cart) {
                // 检查库存
                if ($cart->spec->stock < $cart->quantity) {
                    $this->error("商品[{$cart->goods->title}] 库存不足");
                }

                // 计算商品金额(应用会员折扣)
                $price = $cart->spec->price * $discount;
                $itemAmount = $price * $cart->quantity;
                $order->total_amount += $itemAmount;
                
                // 计算运费
                $order->freight_amount += $cart->goods->freight_price;

                // 添加订单商品
                $orderItems[] = [
                    'goods_id' => $cart->goods_id,
                    'spec_id' => $cart->spec_id,
                    'quantity' => $cart->quantity,
                    'freight_price' => $cart->goods->freight_price,
                    'price' => $price,
                    'amount' => $itemAmount
                ];

                // 扣减库存
                $cart->spec->setDec('stock', $cart->quantity);
                $cart->spec->setInc('sales', $cart->quantity);
                
                // 删除购物车
                $cart->delete();
            }

            // 计算订单应付金额(商品总额+运费)
            $order->order_amount = $order->total_amount + $order->freight_amount;
            
            // 保存订单
            $order->save();
            
            // 保存订单商品
            $order->items()->saveAll($orderItems);

            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('创建成功', ['order_no' => $order->order_no,'order_id'=>$order->id]);
    }

    /**
     * 订单列表
     *
     * @ApiTitle    (订单列表)
     * @ApiSummary  (获取用户订单列表，支持分页和状态筛选)
     * @ApiMethod   (GET)
     * @ApiParams   (name="status", type="integer", required=false, description="订单状态：0=待支付,1=已支付,2=已发货,3=已完成,4=已取消,全部=all")
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词,支持订单号/商品名称")
     * @ApiParams   (name="page", type="integer", required=false, description="页码，默认1")
     * @ApiParams   (name="per_page", type="integer", required=false, description="每页数量，默认10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": 100,          // 总记录数
          "per_page": 10,        // 每页数量
          "current_page": 1,     // 当前页码
          "last_page": 10,       // 最后一页页码
          "data": [{
            "id": 1,             // 订单ID
            "order_no": "202401010001",  // 订单编号
            "total_amount": "100.00",    // 商品总金额
            "freight_amount": "10.00",   // 运费金额
            "order_amount": "110.00",    // 订单总额 商品总额+运费
            "status": 0,         // 订单状态
            "status_text": "待支付", // 订单状态文本
            "createtime": "2024-01-01 00:00:00",  // 创建时间
            "address": "收货地址",     // 收货地址
            "contact": "联系人",      // 收货人
            "phone": "联系电话",      // 联系电话
            "goods_list": [{     // 订单商品列表
              "title": "商品标题",    // 商品名称
              "cover_image": "商品图片",  // 商品图片
              "spec_name": "规格名称",   // 规格名称
              "quantity": 1,      // 购买数量
              "price": "100.00"   // 商品单价
            }]
          }]
        }
      })
     */
    public function index()
    {
        $params = $this->request->get();
        $page = $this->request->get('page', 1);
        $per_page = $this->request->get('per_page', 10);
        $keyword = $this->request->get('keyword', '');

        $where = [
            'user_id' => $this->auth->id,
            'deletetime' => null
        ];
        
        // 状态筛选
        if($params['status'] != 'all' && $params['status'] !== null && $params['status']!== ''){
            $where['status'] = ['=', intval($params['status'])];
        }
        
        // 关键词搜索
        if($keyword){
            $where[] = function($query) use ($keyword) {
                $query->where('o.order_no', 'like', "%{$keyword}%")
                    ->whereOr(function($query) use ($keyword) {
                        $query->whereExists(function($query) use ($keyword) {
                            $query->table('gu_order_item i')
                                ->join('goods g', 'g.id = i.goods_id')
                                ->where('i.order_id = o.id')
                                ->where('g.title', 'like', "%{$keyword}%");
                        });
                    });
            };
            
            // 记录搜索历史
            \app\common\library\SearchLog::record($this->auth->id, $keyword, 'goods_order');
        }

        $total = OrderModel::alias('o')->where($where)->count();
        $list = OrderModel::alias('o')
            ->with(['items.goods', 'items.spec'])
            ->where($where)
            ->page($page, $per_page)
            ->order('o.id DESC')
            ->select();

        // 处理返回数据
        foreach ($list as &$order) {
            $order->visible(['id', 'order_no', 'total_amount', 'freight_amount', 'order_amount', 'status', 'status_text', 'createtime', 'address', 'contact', 'phone','goods_list']);
            $goods_list = [];
            foreach ($order->items as $item) {
                $goods_list[] = [
                    'id' => $item->goods->id,
                    'title' => $item->goods->title,
                    'cover_image' => cdnurl($item->goods->cover_image),
                    'spec_name' => $item->spec->spec_name,
                    'quantity' => $item->quantity,
                    'price' => $item->price
                ];
            }
            $order['goods_list'] = $goods_list;
            //unset($order->items);
        }

        $this->success('', [
            'total' => $total,
            'per_page' => $per_page,
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'data' => $list
        ]);
    }

    /**
     * 订单详情
     * 
     * @ApiTitle    (订单详情)
     * @ApiSummary  (获取订单详细信息，包含商品列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "id": 1,                // 订单ID
          "order_no": "202401010001",  // 订单编号
          "total_amount": "100.00",    // 商品总金额
          "freight_amount": "10.00",   // 运费金额
          "order_amount": "110.00",    // 订单总额 商品总额+运费
          "status": 0,            // 订单状态
          "status_text": "待支付",    // 订单状态文本
          "address": "收货地址",       // 收货地址
          "contact": "联系人",        // 收货人
          "phone": "联系电话",        // 联系电话
          "createtime": "2024-01-01 00:00:00",  // 创建时间
          "pay_end_time": 1672507200, // 支付截止时间 未支付状态下
          "goods_list": [{        // 订单商品列表
            "id": 1,              // 商品ID
            "title": "商品标题",     // 商品名称
            "cover_image": "商品图片", // 商品图片
            "spec_id": 1,         // 规格ID
            "spec_name": "规格名称",  // 规格名称
            "quantity": 1,         // 购买数量
            "price": "100.00",     // 商品单价
            "amount": "100.00"     // 商品总价
          }]
        }
      })
     */
    public function detail()
    {
        $id = $this->request->get('id');
        
        $order = OrderModel::with(['items.goods', 'items.spec'])
            ->where(['id' => $id, 'user_id' => $this->auth->id])
            ->find();

        if (!$order) {
            $this->error('订单不存在');
        }

        // 处理商品列表数据
        $order->visible(['id', 'order_no', 'total_amount' , 'remark' , 'freight_amount', 'pay_end_time','order_amount', 'status', 'status_text', 'address', 'contact', 'phone', 'createtime', 'goods_list']);
        
        // 未支付状态下计算最后支付时间
        if ($order->status == 0) {
            $order['pay_end_time'] = $order->createtime + 7200; // 创建时间加2小时
        }
        $order->createtime = date('Y-m-d H:i:s', $order->createtime);
        $order->goods_list = array_map(function ($item) {
            return [
                'id' => $item->goods->id,
                'title' => $item->goods->title,
                'cover_image' => cdnurl($item->goods->cover_image),
                'spec_id' => $item->spec->id,
                'spec_name' => $item->spec->spec_name,
                'quantity' => $item->quantity,
                'price' => $item->price,
                'amount' => $item->amount
            ];
        }, $order->items);
        unset($order->items);

        $this->success('', $order);
    }

   /**
     * 取消订单
     * 
     * @ApiTitle    (取消订单)
     * @ApiSummary  (取消未支付的订单并恢复所有商品库存)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "取消成功",
        "data": null
      })
     * @ApiNote     (只有未支付的订单才能取消，取消后会恢复所有商品的库存)
     */
    public function cancel()
    {
        $id = $this->request->post('id');
        
        $order = OrderModel::with(['items'])
            ->where([
                'id' => $id,
                'user_id' => $this->auth->id,
                'status' => 0
            ])->find();

        if (!$order) {
            $this->error('订单不存在或无法取消');
        }

        Db::startTrans();
        try {
            // 更新订单状态
            $order->status = 4;
            $order->save();

            // 恢复所有商品的库存和销量
            foreach ($order->items as $item) {
                $spec = GoodsSpec::where([
                    'id' => $item->spec_id,
                    'goods_id' => $item->goods_id
                ])->find();
                
                if ($spec) {
                    $spec->setInc('stock', $item->quantity);
                    $spec->setDec('sales', $item->quantity);
                }
            }
            
            // 创建系统消息
            \app\common\model\SystemMessage::create([
                'user_id' => $order->user_id,
                'type' => 'goods',
                'title' => '订单已取消',
                'content' => "您的订单 {$order->order_no} 已取消",
                'order_id' => $order->id,
                'order_no' => $order->order_no
            ]);

            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error('取消订单失败');
        }

        $this->success('取消成功');
    }

    /**
     * 订单支付
     * 
     * @ApiTitle    (订单支付)
     * @ApiSummary  (发起订单支付)
     * @ApiMethod   (POST)
     * @ApiParams   (name="order_no", type="string", required=true, description="订单编号")
     * @ApiParams   (name="pay_type", type="string", required=true, description="支付方式:wechat=微信支付,alipay=支付宝支付")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "type": "wechat",      // 支付方式
          "params": {}           // 支付参数
        }
      })
     */
    public function pay()
    {
        $orderNo = $this->request->post('order_no');
        $payType = $this->request->post('pay_type');
        
        // 验证支付方式
        if (!in_array($payType, ['wechat', 'alipay'])) {
            $this->error('不支持的支付方式');
        }
        
        $order = OrderModel::where([
            'order_no' => $orderNo,
            'user_id' => $this->auth->id,
            'status' => 0
        ])->find();

        if (!$order) {
            $this->error('订单不存在或已支付');
        }
        if($order->order_amount <= 0){
            $this->error('订单金额错误');
        }
        try {
            // 创建支付
            $notify_url = request()->domain() . '/api/payment/notifyGoods/paytype/' . $payType;
            $result = \addons\epay\library\Service::submitOrder($order->order_amount, $order->order_no, 
                $payType, '商品订单', $notify_url, '','app');
                
            if (!$result) {
                $this->error('创建支付失败');
            }
            $this->success('', [
                'type' => $payType,
                'params' => $payType == 'wechat' ? json_decode($result, true) : $result
            ]);
        } catch (\think\exception\PDOException $e) {
            $this->error('支付失败：' . $e->getMessage());
        }
    }
    /**
     * 直接购买商品
     * 
     * @ApiTitle    (直接创建商品订单)
     * @ApiSummary  (直接购买商品并创建订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="goods_id", type="integer", required=true, description="商品ID")
     * @ApiParams   (name="spec_id", type="integer", required=true, description="规格ID") 
     * @ApiParams   (name="quantity", type="integer", required=true, description="购买数量")
     * @ApiParams   (name="address", type="string", required=true, description="收货地址")
     * @ApiParams   (name="contact", type="string", required=true, description="收货人姓名")
     * @ApiParams   (name="phone", type="string", required=true, description="收货人手机号码")
     * @ApiParams   (name="remark", type="string", required=false, description="订单备注")
     * @ApiReturn   ({
     "code": 1,
        "msg": "创建成功",
        "data": {
        "order_no": "202401010001"  // 订单编号
        }
        })
    */
    public function buy()
    {
        $params = $this->request->post();
        
        // 获取商品和规格信息
        $goods = \app\common\model\Goods::with(['spec' => function($query) use ($params) {
            $query->where('id', $params['spec_id']);
        }])->where('id', $params['goods_id'])->find();
        
        if (!$goods || empty($goods->spec)) {
            $this->error('商品或规格不存在');
        }
        
        $spec = $goods->spec[0];
        
        // 检查库存
        if ($spec->stock < $params['quantity']) {
            $this->error("商品 [{$goods->title}] 库存不足");
        }
        // 获取会员折扣
        $discount = 1;
        if ($this->auth->id) {
            $user = \app\common\model\User::get($this->auth->id);
            if ($user->vip_expire_time > time()) {
                // 获取会员折扣配置
                $vipConfig = \app\common\model\VipConfig::where('id', 1)->find();
                if ($vipConfig) {
                    $discount = $vipConfig->discount;
                }
            }
        }

        // 计算商品价格
        $price = $spec->price * $discount;
        Db::startTrans();
        try {
            // 创建主订单
            $order = new OrderModel;
            $order->order_no = date('YmdHis') . rand(1000, 9999);
            $order->user_id = $this->auth->id;
            $order->address = $params['address'];
            $order->contact = $params['contact'];
            $order->phone = $params['phone'];
            $order->remark = isset($params['remark']) ? $params['remark'] : ''; // 添加备注
            
            // 计算订单金额
            $itemAmount = $price * $params['quantity'];
            $order->total_amount = $itemAmount;
            $order->freight_amount = $goods->freight_price;
            $order->order_amount = $order->total_amount + $order->freight_amount;
            
            // 保存订单
            $order->save();
            
            // 创建订单商品
            $orderItem = [
                'goods_id' => $goods->id,
                'spec_id' => $spec->id,
                'quantity' => $params['quantity'],
                'price' => $price,
                'amount' => $itemAmount
            ];
            
            // 保存订单商品
            $order->items()->save($orderItem);
            
            // 扣减库存
            $spec->setDec('stock', $params['quantity']);
            $spec->setInc('sales', $params['quantity']);
        
            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    
        $this->success('创建成功', ['order_no' => $order->order_no,'order_id'=>$order->id]);
    }
        
    /**
     * 查询物流信息
     * 
     * @ApiTitle    (查询物流信息)
     * @ApiSummary  (根据订单ID查询物流跟踪信息)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "express_company": "顺丰快递",  // 物流公司
          "express_no": "SF123456789",   // 物流单号
          “address”: "收货地址",         // 收货地址
          "contact": "收货人姓名",        // 收货人姓名
          "phone": "联系电话",          // 联系电话
          "list": [{                     // 物流轨迹
            "time": "2024-01-01 12:00:00",  // 时间
            "context": "已签收"             // 物流状态描述
          }]
        }
      })
     */
    public function express()
    {
        $id = $this->request->get('id');
        
        $order = OrderModel::where([
            'id' => $id,
            'user_id' => $this->auth->id,
            'status' => ['in', [2,3]] // 已发货或已完成
        ])->find();

        if (!$order) {
            $this->error('订单不存在或未发货');
        }

        if (empty($order->express_no) || empty($order->express_code)) {
            $this->error('物流信息不存在');
        }

        try {
            $expModle = new \addons\expressquery\library\Expressquery();
            
            $list = $expModle->getExpressList($order->express_code, $order->express_no);
            
            $this->success('', [
                'express_company' => $order->express_company,
                'express_no' => $order->express_no,
                'address' => $order->address,      // 收货地址
                'contact' => $order->contact,      // 收货人
                'phone' => $order->phone,          // 联系电话
                'list' => $list
            ]);
            
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        }
    }
    /**
     * 确认收货
     * 
     * @ApiTitle    (确认收货)
     * @ApiSummary  (确认收货并完成订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "确认收货成功",
        "data": null
    })
    */
    public function confirm()
    {
        $id = $this->request->post('id');
        
        $order = OrderModel::where([
            'id' => $id,
            'user_id' => $this->auth->id,
            'status' => 2  // 已发货状态
        ])->find();
    
        if (!$order) {
            $this->error('订单不存在或无法确认收货');
        }
    
        Db::startTrans();
        try {
            // 更新订单状态为已完成
            $order->status = 3;
            $order->complete_time = time();
            $order->save();
            
            // 创建系统消息
            \app\common\model\SystemMessage::create([
                'user_id' => $order->user_id,
                'type' => 'goods',
                'title' => '订单已完成',
                'content' => "您的订单 {$order->order_no} 已确认收货，感谢您的购买！",
                'order_id' => $order->id,
                'order_no' => $order->order_no
            ]);
    
            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error('确认收货失败');
        }
    
        $this->success('确认收货成功');
    }
    /**
     * 删除订单
     * 
     * @ApiTitle    (删除订单)
     * @ApiSummary  (删除已完成或已取消的订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "删除成功",
        "data": null
        })
        */
    public function delete()
    {
        $id = $this->request->post('id');
        
        $order = OrderModel::where([
            'id' => $id,
            'user_id' => $this->auth->id,
            'deletetime' => null
        ])->where('status', 'in', [3,4])  // 已完成或已取消
        ->find();

        if (!$order) {
            $this->error('订单不存在或无法删除');
        }

        // 软删除订单
        $order->deletetime = time();
        if ($order->save()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    /**
     * 再次购买
     * 
     * @ApiTitle    (再次购买)
     * @ApiSummary  (根据已有订单信息创建新订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="原订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "创建成功",
        "data": {
          "order_no": "202401010001"  // 新订单编号
        }
      })
     */
    public function rebuy()
    {
        $id = $this->request->post('id');
        
        // 获取原订单信息
        $oldOrder = OrderModel::with(['items.goods', 'items.spec'])
            ->where(['id' => $id, 'user_id' => $this->auth->id])
            ->find();

        if (!$oldOrder) {
            $this->error('订单不存在');
        }

        Db::startTrans();
        try {
            // 创建新订单
            $order = new OrderModel;
            $order->order_no = date('YmdHis') . rand(1000, 9999);
            $order->user_id = $this->auth->id;
            $order->address = $oldOrder->address;
            $order->contact = $oldOrder->contact;
            $order->phone = $oldOrder->phone;
            $order->total_amount = 0;
            $order->freight_amount = 0;

            // 获取会员折扣
            $discount = 1;
            if ($this->auth->id) {
                $user = \app\common\model\User::get($this->auth->id);
                if ($user->vip_expire_time > time()) {
                    $vipConfig = \app\common\model\VipConfig::where('id', 1)->find();
                    if ($vipConfig) {
                        $discount = $vipConfig->discount;
                    }
                }
            }

            // 创建订单商品
            $orderItems = [];
            foreach ($oldOrder->items as $item) {
                // 检查商品和规格是否还存在
                $goods = \app\common\model\Goods::where('id', $item->goods_id)->find();
                $spec = \app\common\model\GoodsSpec::where(['id' => $item->spec_id, 'goods_id' => $item->goods_id])->find();
                
                if (!$goods || !$spec) {
                    throw new \Exception("商品已下架或规格不存在");
                }
                
                // 检查库存
                if ($spec->stock < $item->quantity) {
                    throw new \Exception("商品 [{$goods->title}] 库存不足");
                }

                // 计算商品金额(使用最新价格和会员折扣)
                $price = $spec->price * $discount;
                $itemAmount = $price * $item->quantity;
                $order->total_amount += $itemAmount;
                
                // 计算运费
                $order->freight_amount += $goods->freight_price;

                // 添加订单商品
                $orderItems[] = [
                    'goods_id' => $item->goods_id,
                    'spec_id' => $item->spec_id,
                    'quantity' => $item->quantity,
                    'price' => $price,
                    'amount' => $itemAmount
                ];

                // 扣减库存
                $spec->setDec('stock', $item->quantity);
                $spec->setInc('sales', $item->quantity);
            }

            // 计算订单应付金额
            $order->order_amount = $order->total_amount + $order->freight_amount;
            
            // 保存订单
            $order->save();
            
            // 保存订单商品
            $order->items()->saveAll($orderItems);

            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('创建成功', ['order_no' => $order->order_no]);
    }
}